import React, { useRef, useState, useEffect } from 'react';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import { Button, Switch, message, Modal, Form, Image, Cascader } from 'antd';
import ProTable from '@ant-design/pro-table';
import { PageContainer } from '@ant-design/pro-layout';
import AliyunOSSUpload from '@/components/AliyunOSSUpload';
import Editor from '@/components/Editor';
import {
  getGoods,
  goodsOn,
  goodsRecommend,
  addGoods,
  updateGoods,
  getGoodDetial,
  getCategory,
} from '@/services/goods';
import ProForm, { ProFormDigit, ProFormText, ProFormTextArea } from '@ant-design/pro-form';

export default () => {
  const [form] = Form.useForm();
  const [goodsform] = Form.useForm();
  const actionRef = useRef();
  let [options, setOptions] = useState([]);
  let [GoodDetial, setGoodDetial] = useState([]);
  useEffect(async () => {
    const reponse = await getCategory();
    setOptions(reponse);
  }, []);

  const [isModalVisible, setisModalVisible] = useState(false);
  const [isModalVisibleEdit, setisModalVisibleEdit] = useState(false);
  const ChangModel = (name) => {
    if (name == 'edit') {
      setisModalVisibleEdit(!isModalVisibleEdit);
    } else {
      setisModalVisible(!isModalVisible);
    }
  };
  const getData = async (params) => {
    const response = await getGoods(params);
    console.log(response);
    return {
      data: response.data,
      success: true,
      total: response.meta.pagination.total_pages,
    };
  };
  const setCoverKey = (key) => {
    console.log(key);
    goodsform.setFieldsValue({
      cover: key,
    });
  };
  const setdetailsKey = (key) => {
    console.log(key);
    goodsform.setFieldsValue({
      details: key,
    });
  };
  const columns = [
    {
      title: '图片',
      dataIndex: 'cover_url',
      hideInSearch: true,
      render: (_, record) => (
        <Image
          width={80}
          src={record.cover_url}
          placeholder={<Image preview={false} src={record.cover_url} width={200} />}
        />
      ),
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '价格',
      dataIndex: 'price',
      hideInSearch: true,
    },
    {
      title: '库存',
      dataIndex: 'stock',
      hideInSearch: true,
    },
    {
      title: '销量',
      dataIndex: 'sales',
      hideInSearch: true,
    },
    {
      title: '是否上架',
      dataIndex: 'is_on',
      valueType: 'radioButton',
      valueEnum: {
        1: { text: '已上架', status: 1 },
        0: { text: '未上架', status: 0 },
      },
      render: (_, record) => (
        <Switch
          checkedChildren="已上架"
          unCheckedChildren="未上架"
          defaultChecked={record.is_on === 1}
          onChange={async () => {
            const respnse = await goodsOn(record.id);
            if (respnse.status === undefined) {
              message.success('操作成功');
            } else {
              message.error('操作失败');
            }
          }}
        />
      ),
    },
    {
      title: '是否推荐',
      dataIndex: 'is_recommend',
      valueType: 'radioButton',
      valueEnum: {
        1: { text: '已推荐', status: 1 },
        0: { text: '未推荐', status: 0 },
      },
      render: (_, record) => (
        <Switch
          checkedChildren="推荐"
          unCheckedChildren="未推荐"
          defaultChecked={record.is_recommend === 1}
          onChange={async () => {
            const respnse = await goodsRecommend(record.id);
            if (respnse.status === undefined) {
              message.success('操作成功');
            } else {
              message.error('操作失败');
            }
          }}
        />
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      hideInSearch: true,
    },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={async () => {
            const response = await getGoodDetial(record.id);
            const { pid, id } = response.category;
            let defaultCatefory = pid === 0 ? [id] : [pid, id];
            setGoodDetial(response);
            form.setFieldsValue({
              ...response,
              category_id: defaultCatefory,
            });
            ChangModel('edit');
            console.log(response);
          }}
        >
          编辑
        </a>,
      ],
    },
  ];
  return (
    <PageContainer>
      <ProTable
        columns={columns}
        actionRef={actionRef}
        request={async (params = {}, sort, filter) => getData(params)}
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        pagination={{
          pageSize: 10,
        }}
        dateFormatter="string"
        headerTitle="商品列表"
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => {
              ChangModel();
            }}
          >
            新建
          </Button>,
        ]}
      />
      <Modal title="添加商品" visible={isModalVisible} onCancel={ChangModel} footer={null}>
        <ProForm
          form={goodsform}
          onFinish={async (values) => {
            values.category_id = values.category_id[1]
              ? values.category_id[1]
              : values.category_id[0];
            console.log(values);
            const response = await addGoods(values);
            if (response.status === undefined) {
              message.success('添加成功');
              ChangModel();
              actionRef.current.reload();
              return true;
            } else if (response.status === 422) {
              let msg = '';
              console.log(response.errors);
              for (const key in response.errors) {
                msg += response.errors[key][0];
              }
              message.error(msg);
            }
            // console.log(values);
          }}
        >
          <ProForm.Item
            name="category_id"
            label="分类"
            placeholder="请输入分类"
            rules={[{ required: true, message: '请输入分类' }]}
          >
            <Cascader
              options={options}
              fieldNames={{ label: 'name', value: 'id' }}
              placeholder="请选择分类"
            />
          </ProForm.Item>
          <ProFormText
            name="title"
            label="标题"
            placeholder="请输入标题"
            rules={[{ required: true, message: '请输入标题' }]}
          />
          <ProFormTextArea
            name="description"
            label="描述"
            placeholder="请输入描述"
            rules={[{ required: true, message: '请输入描述' }]}
          />
          <ProFormDigit
            name="price"
            label="价格"
            min={0}
            max={9999}
            placeholder="请输入价格"
            rules={[{ required: true, message: '请输入价格' }]}
          />
          <ProFormDigit
            name="stock"
            label="库存"
            min={0}
            max={9999}
            placeholder="请输入库存"
            rules={[{ required: true, message: '请输入库存' }]}
          />
          <ProForm.Item
            name="cover"
            label="封面图"
            rules={[{ required: true, message: '请上传封面图' }]}
          >
            <div>
              <AliyunOSSUpload accept="image/*" showUploadList={true} setCoverKey={setCoverKey}>
                <Button icon={<UploadOutlined />}>上传封面图</Button>
              </AliyunOSSUpload>
            </div>
          </ProForm.Item>
          <ProForm.Item
            name="details"
            label="详情"
            rules={[{ required: true, message: '请输入详情' }]}
          >
            <Editor setdetailsKey={setdetailsKey} />
          </ProForm.Item>
        </ProForm>
      </Modal>
      <Modal
        title="添加用户"
        visible={isModalVisibleEdit}
        onCancel={() => ChangModel('edit')}
        footer={null}
      >
        <ProForm
          form={form}
          onFinish={async (values) => {
            values.category_id = values.category_id[1]
              ? values.category_id[1]
              : values.category_id[0];
            console.log(values);
            const response = await updateGoods(GoodDetial.id, values);
            if (response.status === undefined) {
              message.success('修改成功');
              ChangModel('edit');
              actionRef.current.reload();
              return true;
            } else if (response.status === 422) {
              let msg = '';
              console.log(response.errors);
              for (const key in response.errors) {
                msg += response.errors[key][0];
              }
              message.error(msg);
            }
          }}
        >
          <ProForm.Item
            name="category_id"
            label="分类"
            placeholder="请输入分类"
            rules={[{ required: true, message: '请输入分类' }]}
          >
            <Cascader
              options={options}
              fieldNames={{ label: 'name', value: 'id' }}
              placeholder="请选择分类"
            />
          </ProForm.Item>
          <ProFormText
            name="title"
            label="标题"
            placeholder="请输入标题"
            rules={[{ required: true, message: '请输入标题' }]}
          />
          <ProFormTextArea
            name="description"
            label="描述"
            placeholder="请输入描述"
            rules={[{ required: true, message: '请输入描述' }]}
          />
          <ProFormDigit
            name="price"
            label="价格"
            min={0}
            max={9999}
            placeholder="请输入价格"
            rules={[{ required: true, message: '请输入价格' }]}
          />
          <ProFormDigit
            name="stock"
            label="库存"
            min={0}
            max={9999}
            placeholder="请输入库存"
            rules={[{ required: true, message: '请输入库存' }]}
          />
          <ProForm.Item
            name="cover"
            label="封面图"
            rules={[{ required: true, message: '请上传封面图' }]}
          >
            <div>
              <AliyunOSSUpload accept="image/*" showUploadList={true} setCoverKey={setCoverKey}>
                <Button icon={<UploadOutlined />}>上传封面图</Button>
              </AliyunOSSUpload>
              {!GoodDetial.cover_url ? '' : <Image width={200} src={GoodDetial.cover_url} />}
            </div>
          </ProForm.Item>
          <ProForm.Item
            name="details"
            label="详情"
            rules={[{ required: true, message: '请输入详情' }]}
          >
            <Editor setdetailsKey={setdetailsKey} content={GoodDetial.details} />
          </ProForm.Item>
        </ProForm>
      </Modal>
    </PageContainer>
  );
};
